package com.ly.sms.controller.login;

import com.ly.sms.model.ApiResponse;
import com.ly.sms.model.RspEnum;
import com.ly.sms.model.SmsRequest;
import com.ly.sms.model.SmsResp;
import com.ly.sms.service.SmsService;
import com.ly.sms.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author ly
 * @Date 2022-03-26 17:58
 */
@RestController
@RequestMapping(path = {"/"})
public class SmsController extends LoginController {

  @Autowired
  private SmsService smsService;

  @RequestMapping(path = {"/directmessage"})
  @ResponseBody
  public ApiResponse directmessage(@RequestParam(value = "tels", required = true) String tels,
      @RequestParam(value = "qos", required = true) String qos, @RequestParam(value = "userName", required = true) String userName,
      @RequestParam(value = "sessionId", required = true) String sessionId, @RequestBody SmsRequest request) {

    // 参数校验
    if (StringUtils.isBlank(qos) || StringUtils.isBlank(userName) || StringUtils.isBlank(tels) ||
        StringUtils.isBlank(sessionId) || StringUtils.isBlank(userName) || StringUtils.isBlank(tels) ||
        StringUtils.isBlank(request.getTitle()) || StringUtils.isBlank(request.getContent())) {
      return new SmsResp(RspEnum.PARAM_ERROR.getCode(), RspEnum.PARAM_ERROR.getMsg());
    }

    request.setQos(qos);
    request.setSessionId(sessionId);
    request.setTels(tels);
    request.setUserName(userName);

    // 未注册用户
    if (users.get(request.getUserName()) == null) {
      return new ApiResponse(RspEnum.NOT_REGIST.getCode(), RspEnum.NOT_REGIST.getMsg());
    }

    // 未登陆
    String tk = token.get(request.getUserName());
    if (tk == null) {
      return new ApiResponse(RspEnum.NOT_LOGIN.getCode(), RspEnum.NOT_LOGIN.getMsg());
    }

    if (!tk.equals(request.getSessionId())) {
      return new ApiResponse(RspEnum.TOKEN_ERROR.getCode(), RspEnum.TOKEN_ERROR.getMsg());
    }
    SmsResp smsResp = smsService.sendMsg(request);

    System.out.println("发送结果:" + JsonUtils.toJson(smsResp));

    return smsResp;
  }


}
